package dao;

import entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.Arrays;
import java.util.List;

@Repository
public class UserDaoImpl implements UserDao{
    //获取jdbcTemplate
    @Autowired
    private JdbcTemplate jdbcTemplate;

//添加用户
    public void add(User user) {
        String sql="insert into user(id,uname,upass,type) values(?,?,?,?)";
        Object[] args={user.getId(),user.getUname(),user.getUpass(),user.getType()};
        int res=jdbcTemplate.update(sql,args);
        System.out.println(res);
    }
//根据用户id删除用户
    public void delete(int id) {
        String sql="delete from user where id=?";
        int res = jdbcTemplate.update(sql,id);
        System.out.println(res);
    }
//修改用户
    public void update(User user) {
    String sql="update user set uname=?,upass=?,type=? where id=?";
    Object[] args={user.getUname(),user.getUpass(),user.getType(),user.getId()};
    int res=jdbcTemplate.update(sql,args);
        System.out.println(res);
    }
//查询表的行数
    public int selectCount() {
        String sql="select count(*) from user";
        int res = jdbcTemplate.queryForObject(sql,Integer.class);
        System.out.println(res);
        return res;
    }

    public User query(int id) {

        String sql = "select * from user where id = ?";
        User user = jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<User>(User.class),id);
        return user;
    }

    public List<User> queryList() {
        String sql = "select * from user";
        List<User> userList = jdbcTemplate.query(sql,new BeanPropertyRowMapper<User>(User.class));
        return userList;
    }

    public void batchAddUsers(List<Object[]> batchArgs){
        String sql="insert into user(id,uname,upass,type) values(?,?,?,?)";
        int[] ints = jdbcTemplate.batchUpdate(sql,batchArgs);
        System.out.println(ints);
    }

    public void batchUpdateUser(List<Object[]> batchArgs) {
        String sql="update user set uname=?,upass=?,type=? where id=?";
        int[] ints = jdbcTemplate.batchUpdate(sql,batchArgs);
        System.out.println(Arrays.toString(ints));
    }

    public void batchDeleteUser(List<Object[]> batchArgs) {
        String sql="delete from user where id=?";
        int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
        System.out.println(Arrays.toString(ints));
    }
}